package com.heima.admin.gateway.filter;

import com.heima.common.dtos.Payload;
import com.heima.common.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.JsonSerializableWithType;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取当前请求
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2. 获取请求路径
        String uriPath = request.getURI().getPath();
        log.info("请求路径={}", uriPath);
        //3. 判断当前请求路径是否已经登陆
        if (uriPath.contains("/login/in")) {
            // 直接放行
            return chain.filter(exchange);
        }
        //4. 不是登陆请求的话，需要验证token
        String token = request.getHeaders().getFirst("token");
        log.info("token={}", token);
        if (StringUtils.isBlank(token)) {
            // 为空的话，返回401未授权状态
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5. 校验token
        try {
            Payload payload = JwtUtils.getInfoFromToken(token);
            Integer userId = payload.getUserId();
            log.info("userId={}", userId);
            //5.1 将用户id放入header中
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", String.valueOf(userId));
            }).build();
            exchange.mutate().request(serverHttpRequest).build();
        } catch (Exception e) {
            log.error("验证token出现错误！");
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
